<template>
    <div class="home">
        <van-nav-bar title="音乐列表">
            <van-icon name="search" slot="right" @click="search"/>
        </van-nav-bar>
        <music-list :music-list="musicList"></music-list>
    </div>
</template>

<script>
    import axios from '../http/axios'
    import MusicList from '../components/MusicList'
    export default {
        name: 'home',
        components: {
            MusicList
        },
        data() {
            return {
                audioUrl: '',
                isPlay: false,
                musicList: [],
                currentPlayIndex: -1,
            }
        },
        methods: {
            checkMusic(url, i) {
                this.musicList.forEach((item, index) => {
                    item.isPlay = false;
                    if (index === i && this.currentPlayIndex !== i) item.isPlay = true;
                });
                if (this.currentPlayIndex === i) {
                    this.currentPlayIndex = -1;
                    document.getElementById('aud').pause();
                    return;
                }
                this.currentPlayIndex = i;
                this.audioUrl = url;
                this.$nextTick(() => {
                    document.getElementById('aud').play();
                })
            },
            search() {
                this.$router.push('/search');
            }
        },
        created() {
            axios.get('/api/getMusicList')
            .then(res => {
                this.musicList = res.data.data.map(item => {
                    return Object.assign(item, {isPlay: false})
                });
                this.$store.commit('updateMusicList', this.musicList)
            })
        }
    }
</script>

<style>
    .home {
        width: 100vw;
        background-color: #f7f8fa;
    }
</style>
